require 'ServerModel'
require 'ServerView'
require 'json/pure'

class ServerControl
  
  def initialize(view,model)
    @serverView = view
    @serverModel = model
  end
  
  def request(env)
    [200, {"Content-Type" => "text/plain"}, 'html']
  end
  
  def server_mode_fetch(path)
    page = @serverView.getAllHTML(path)
    return page
  end
  
  def cdnames()
    dbresp = @serverModel.getCandidateNames()
    dbresp = @serverView.buildResponse(dbresp)
    return dbresp
  end
  
  def cdtotal()
    dbresp = @serverModel.getNationwideTotals()
    dbresp = @serverView.buildResponse(dbresp)
    return dbresp
  end
  
  def detailnw()
    dbresp = @serverModel.getDetailedNationwideReport()
    dbresp = @serverView.buildResponse(dbresp)
    return dbresp
  end
  
  def database(uripieces,method,payload)
    msg = ""
    
    case method
      when "GET"
        #msg << "Searched into DB\n" << "URI Piece : "<< uripieces[2]  #Debugging test message
        if (self.respond_to? uripieces[2])
          dbresp = self.send(uripieces[2])
          puts dbresp.to_s
        end
        status = 200
        return [status, {"Content-Type" => "application/json"}, dbresp.to_s]
      when "POST" 
        msg << "Inserted into DB\n" << "\nPayload"<< payload<< "\n"
        json = JSON.parse(payload)
        @serverModel.addNewTable(json)
        status = 201
      when "PUT" 
        msg << "Updated in DB\n" << "\nPayload"<< payload<< "\n"
        jeisonManuel = JSON.parse(payload)
        @serverModel.updateTable(jeisonManuel)
        status = 202
      when "DELETE" 
        msg << "Deleted on DB\n" << "\nPayload"<< payload<< "\n"
        jeisonAlexanderr = JSON.parse(payload)
        @serverModel.delTable(jeisonAlexanderr)
        status = 204
    end
    return [status, {"Content-Type" => "text/plain"}, msg]
  end
  
def notify(env)
      httpRequest = Rack::Request.new(env)
      path = env["PATH_INFO"]
      method = env["REQUEST_METHOD"]
      uriPieces = path.split('/')
      payload = env["rack.input"].gets

      
      case
        when(path == "")
          return [200, {"Content-Type" => "text/plain"}, env.to_s]
        when(path == "/")
          html = server_mode_fetch("main")
          return [200, {"Content-Type" => "text/html"}, html]
        when(path.include? "database")
          return database(uriPieces,method,payload)
        when (self.respond_to? path)
          self.send(path,env)
        else
          html = server_mode_fetch(path)
          return [404, {"Content-Type" => "text/plain"}, "Page Not Found"] if html == "FileNotFound"
          return [200, {"Content-Type" => "text/html"}, html]
      end
      
    end
    
  
end